<template>
    <el-form ref="userRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="手机号码：" prop="phonenumber">
          <el-input v-model="form.phonenumber" maxlength="11"/>
        </el-form-item>
        <el-form-item label="用户邮箱：" prop="email">
          <el-input v-model="form.email" maxlength="50"/>
        </el-form-item>
        <el-form-item label="其他：" prop="remark">
            <el-input v-model="form.remark" maxlength="50"/>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="handleSubmit">保存</el-button>
    
        </el-form-item>
      </el-form>
</template>
  
<script setup>
import { ref, defineProps } from "vue";
import requestUtil from '../../../utils/request'
import { ElMessage } from 'element-plus'
import Cookies from "js-cookie";
import qs from "qs";
const props = defineProps({
  user: {
    type: Object,
    default: () => {},
    required: true,
  },
})
const form = ref({
  id: -1,
  phonenumber: '',
  email: '',
  remark: ''
})
const userRef = ref(null)

//初始化from
form.value = props.user;
// 表单检测
const rules = ref({
  email: [{required: true, message: "邮箱地址不能为空", trigger: "blur"}, {
    type: "email",
    message: "请输入正确的邮箱地址",
    trigger: ["blur", "change"]
  }],
  phonenumber: [{required: true, message: "手机号码不能为空", trigger: "blur"}, {
    pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
    message: "请输入正确的手机号码",
    trigger: "blur"
  }],
  remark: [{required: true, message: "其他不能为空", trigger: "blur"}],
});

// 保存修改
const handleSubmit = () => {

userRef.value.validate(async (valid) => {
  if (valid) {
    let result = await requestUtil.post("updateUser?",qs.stringify(form.value) );
    let data = result.data;
    if (data.code == 200) {
      ElMessage.success("执行成功！")
      const { password ,...newUser } =data.user 
      Cookies.set("email", form.value.email, { expires: 30 });
      window.sessionStorage.setItem("currentUser", JSON.stringify(newUser))
    }
  }
})
}
</script>
  
<style scoped>
</style>